<template>
  <!--电梯档案--电梯列表-->
  <div style="height: 100%;position: relative;">
    <HeadTop></HeadTop>
    <div class="content-area el-list">
      <div class="search-area">
        <!-- 查询页面  -->
        <div class="search-content">
          <div class="search-item">
            <span>注册代码:</span>
            <el-input placeholder="请输入内容" v-model="searchData.signInCode" clearable></el-input>
          </div>
          <div class="search-item">

            <unit-data @transferSelect="transferSelectUsing" @setStatus="setInputChangeUsing"
                       @setInputEmpty="setInputEmptyUsing"
                       :childName="unitDataNameUsing" :searchType="2"></unit-data>

          </div>
          <div class="search-item">

            <unit-data @transferSelect="transferSelectMaintain" @setStatus="setInputChangeMaintain"
                       @setInputEmpty="setInputEmptyMaintain"
                       :childName="unitDataNameMaintain" :searchType="1"></unit-data>
          </div>
          <!--date start-->
          <div class="search-item search-time"><span>开始日期(初检):</span>
            <el-date-picker
              v-model="searchData.startDate"
              align="right"
              type="date"
              placeholder="选择开始日期">
            </el-date-picker>
          </div>
          <div class="search-item search-time"><span>结束日期(初检):</span>
            <el-date-picker
              v-model="searchData.endDate"
              align="right"
              type="date"
              placeholder="选择结束日期">
            </el-date-picker>
          </div>
          <areaSelect v-on:getNowAreaPosition="getArea" :areaText="areaText"></areaSelect>
        </div>
        <div class="search-footer">
          <button class="search-btn" @click="getEleTestingData">查询</button>
        </div>
      </div>


      <!--内容-->
      <div class="main-content">
        <div class="content-info" style="width: 100%">

          <!-- 111:表格数据与翻页合并模块 -->
          <DataTable :childLoad="parentLoad" :dataTableObj="dataTableObj" v-on:getPageNo="searchByPageNo"
                     v-on:selectChange="checkChange"
                     v-on:getPageSize="searchByPageSize" v-on:handlePageReload="pageReload"
                     ref="chooseEle">
            <!--除查询外的操作-->
            <div slot="operate">
              <div class="some-operate">
                <button class="some-btn some-btn-import" @click="showUploadDialog" v-if="pagePower['002001003']">导入Excel</button>
                <button class="some-btn some-btn-export" @click="exportQrode" v-if="pagePower['002001004']">导出电梯二维码</button>
                <!--<button class="some-btn" @click="addEleFile" v-if="addElePower">添加电梯</button>-->
              </div>
            </div>
            <!-- 额外的操作以及其他因素 -->
            <div>
              <el-table-column type="selection" width="55" fixed="left"></el-table-column>
              <el-table-column fixed="right" label="二维码" align="center" width="60">
                <template slot-scope="scope">
                  <div class="img-position">
                    <el-popover
                      ref="popover1"
                      placement="top-end"
                      width="100"
                      popper-class="el_pop"
                      trigger="hover">
                      <div>
                        <qr-code :text="eleUrlRequest + scope.row.registerCode"></qr-code>
                      </div>
                    </el-popover>

                    <el-button type="text" v-popover:popover1>
                      <div class="min-img-position">
                        <img class="min-img" src="../../../../static/img/qrcode_icon.jpg"/>
                      </div>
                    </el-button>
                  </div>
                </template>
              </el-table-column>
              <el-table-column fixed="right" align="center" label="操作" width="130">
                <template slot-scope="scope">
                  <div class="item-route">
                    <div class="item-route-link"
                         v-if="pagePower['002001001']"
                         @click="$goRoute('/manage/eleFiles/eleList/eleDetail?registerCode='+ scope.row.registerCode)">
                      查看详情
                    </div>
                    <div class="item-route-link"
                         v-if="pagePower['002001002']"
                         @click="goEleEdit('/manage/eleFiles/eleEdit?registerCode='+ scope.row.registerCode)">档案修改
                    </div>
                  </div>
                </template>
              </el-table-column>
            </div>
          </DataTable>

        </div>
      </div>
    </div>

    <el-dialog title="上传" :visible.sync="dialogVisible">
      <el-upload
        :action="uploadUrl"
        multiple
        :headers="uploadHeader"
        :limit="1"
        :data="uploadData"
        :on-exceed="handleExceed"
        :before-upload="beforeUpload"
        :on-success="successUpload"
        :on-error="errorUpload"
        :file-list="fileList">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传xlsx文件,大小限制5000kb</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>

    </el-dialog>
  </div>
</template>
<script>
  import areaSelect from "../../../components/areaSelect/areaSelect"
  // 表格数据
  import DataTable from "../../../components/dataTable/dataTable"
  import com from '../../../js/common'
  import HeadTop from "../../../components/head-top/head-top"
  import moment from 'moment'
  import {getEleList} from '@/api/getData'
  import unitData from "../../../components/unitData/unitData"
  // 二维码
  import Vue from 'vue'
  import VueQRCodeComponent from 'vue-qrcode-component'

  Vue.component('qr-code', VueQRCodeComponent)


  export default {
    name: 'eleTesting',
    components: {
      DataTable,
      areaSelect,
      HeadTop,
      unitData
    },
    data() {
      return {
        eleUrlRequest: 'http://114.55.125.45/dist/eleMsg.html?eleCode=',
        // 两个字段
        unitDataNameUsing: '物业单位',
        unitDataNameMaintain: '维保单位',
        parentLoad: '加载中...',    // 加载状态
        // 权限
        pagePower: JSON.parse(com.getStore('pagePowers'))['002001'] ? JSON.parse(com.getStore('pagePowers'))['002001'] : {},
        addElePower: JSON.parse(com.getStore('pagePowers'))['002002'] ? JSON.parse(com.getStore('pagePowers'))['002002'] : false,
        //  111:表格组件数据
        dataTableObj: {

          // 表格数据
          tableData: [],
          // 表格标题
          tableColumns: [
            { // (后端提供字段名称)
              text: '序号',
              width: '50',
              attributeName: 'index'
            },
            {
              text: '注册代码',
              width: '150',
              attributeName: 'registerCode'
            },
            {
              text: '电梯名称',
              width: '110',
              attributeName: 'argsName'
            },
            {
              text: '街道',
              width: '70',
              attributeName: 'street'
            },
            {
              text: '社区',
              width: '80',
              attributeName: 'community'
            },
            {
              text: '使用单位',
              width: '160',
              attributeName: 'usingName'
            },
            {
              text: '维保单位',
              width: '160',
              attributeName: 'maintenanceUnit'
            },
            {
              text: '电梯地址',
              width: '130',
              attributeName: 'address'
            },
            {
              text: '初检日期',
              width: '90',
              attributeName: 'installCheckNextDate'
            }
          ],
          // 翻页的数据
          pageObj: {
            // 每页分为几条数据
            pageSize: 10,
            // 总共多少数据
            pageNum: 0,
            pageNo: 1,
            searchStatus: 2,
          }
        },
        searchData: { // 输入字段(前端字段)
          signInCode: '',  // 注册代码
          userUnit: '',    // 使用单位
          mtcUnit: '',     // 维保单位
          startDate: '',   // 开始时间
          endDate: ''      // 结束时间
        },
        searchMsg: { // 输入字段(后台字段)
          registerCode: '',       // 注册代码
          usingCode: '',          // 使用单位
          maintenanceUnitCode: '',    // 维保单位          startDate: '',           // 开始时间
          endDate: '',              // 结束时间
          areaCode: '',

        },
        // 区域选择
        areaText: '区域选择:',
        dialogVisible: false,
        uploadUrl: `${com.basePath}/elevator-web/excel/upload`,
        uploadHeader: {
          clientType: 'WEB',
          loginToken: com.getStore('loginToken'),
          userId: com.getStore('userId')
        },
        fileList: [],
        uploadData: {
          file: 'xlsx'
        },
        selectEleCode: []  // 导出时选中的电梯
      }
    },
    /* 页面装载中,此时获取后端数据 */
    created() {

      this.getEleTestingData()
    },
    mounted() {

    },
    methods: {

      // 选择校验
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      // 上传前校验
      beforeUpload(file) {
        // this.uploadData.file = 'xlsx'
        const index1 = file.name.lastIndexOf(".");
        const index2 = file.name.length;
        const suffix = file.name.substring(index1 + 1, index2)
        if (suffix !== 'xlsx') {
          this.$message({
            type: 'warning',
            message: ` ${ file.name }不符合上传要求`
          });
          return false
        }
        if (file.size / 1024 >= 5000) {
          this.$message({
            type: 'warning',
            message: `${ file.name }大小应该小于5000kb`
          });
          return false
        }
      },
      // 成功上传
      successUpload(res) {
        if (res.code !== '200') {
          this.$message.error(`${res.message}`);
          this.dialogVisible = false
          return
        }
        this.$message({
          type: 'success',
          message: `文件上传成功`
        });
        this.dialogVisible = false
      },
      // 上传失败
      errorUpload(err, file, fileList) {
        this.$message({
          type: 'error',
          message: `文件上传失败,xlsx应满足格式要求`
        });
      },
      // 展示上传文件框
      showUploadDialog() {
        this.dialogVisible = true
      },
      // check查询条件
      checkSearchItem() {
        if (this.searchData.startDate && this.searchData.endDate) {
          if (!moment(this.searchData.startDate).isBefore(this.searchData.endDate)) {
            this.$message.warning('开始时间应小于结束时间')
            return false
          }
        }
        return true
      },
      // 获取页面所需数据
      getEleTestingData(obj) {

        if (!this.checkSearchItem()) {
          return
        }
        this.dataTableObj.pageObj.searchStatus = 2
        this.searchMsg.startDate = this.searchData.startDate
        this.searchMsg.endDate = this.searchData.endDate
        this.searchMsg.registerCode = this.searchData.signInCode  // 注册代码
        let self = this;
        // 获取网络请求
        getEleList({
          pageNo: self.dataTableObj.pageObj.pageNo,
          pageSize: self.dataTableObj.pageObj.pageSize,
          condition: self.searchMsg
        }).then((data) => {
          self.dataTableObj.pageObj.searchStatus = 1
          // 后台回调数据
          let info = data.data.data;
          let infoArr = info.data;

          if (infoArr.length > 0) {
            const pageSize = self.dataTableObj.pageObj.pageSize
            const pageNo = self.dataTableObj.pageObj.pageNo
            // 此时进行重显
            let selectRow = []
            infoArr.forEach((i, t) => {
              i.index = (t + 1) + (pageNo - 1) * pageSize
              i.installCheckNextDate = moment(i.installCheckNextDate).format('YYYY-MM-DD')
              // 当前数据中的选中数据
              this.selectEleCode.forEach((v) => {
                if (v === i.registerCode) {
                  selectRow.push(i)
                }
              })
            })
            if (selectRow.length > 0) {
              this.toggleSelection(selectRow)
            }
          } else {
            self.parentLoad = '暂无数据'    // loading(暂无数据)
          }
          self.dataTableObj.tableData = infoArr
          self.dataTableObj.pageObj.pageNum = info.totalRecord
        }).catch((data) => {
          this.$message.error(data.data.message)
          self.parentLoad = data.data.message    // loading(查询失败)
          self.dataTableObj.pageObj.searchStatus = 0
        })
      },
      // 每页多少内容
      searchByPageSize(val) {
        this.dataTableObj.pageObj.pageSize = val
        this.getEleTestingData() // 翻页方法
      },
      // 切换第几页
      searchByPageNo(val) {
        this.dataTableObj.pageObj.pageNo = val
        this.getEleTestingData() // 翻页方法
      },
      // 获取当前选中区域
      getArea(res) { // 获取查询地址
        this.searchMsg.areaCode = res.code
      },
      // 选择物业单位
      transferSelectUsing(item) {
        this.searchMsg.usingCode = item.code
      },
      // 选择物业单位变化后
      setInputChangeUsing() {
        this.searchMsg.usingCode = -1
      },
      // 选择物业单位变化后置空
      setInputEmptyUsing() {
        this.searchMsg.usingCode = ''
      },
      // 选择维保单位
      transferSelectMaintain(item) {
        this.searchMsg.maintenanceUnitCode = item.code
      },
      // 选择维保单位
      setInputEmptyMaintain() {
        this.searchMsg.maintenanceUnitCode = ''
      },
      // 选择维保单位
      setInputChangeMaintain() {
        this.searchMsg.maintenanceUnitCode = -1
      },
      goEleEdit(url) {
        // 存储当前选择中的板块
        this.$goRoute(url)
      },
      // 跳转添加电梯页面
      addEleFile() {

      },

      // 勾选以及对应的回显
      checkChange(val) {
        let checkCodes = '';
        val.forEach((i) => {
          console.log(i)
          if (checkCodes !== '') {
            checkCodes = checkCodes + '\n' + i.registerCod + '-' + i.address;
          } else {
            checkCodes = i.registerCode+ '-'+ i.address;
          }
          this.selectEleCode.push(i.registerCode + '-' + i.address)
        })

        // 每次进行去重
        this.selectEleCode = com.uniqueArr(this.selectEleCode )
        // 去重之后将去重的数据传递给后台

        this.dataTableObj.checkCodes = this.selectEleCode.reduce((pos, value) => {
          return pos + '\n' + value
        }, '');
      },

      // 电梯二维码导出
      exportQrode() {
        if(!this.dataTableObj.checkCodes){
          this.$message.warning('请先勾选电梯')
          return
        }
        console.log(this.dataTableObj.checkCodes)
        com.axio({
          method: 'post',
          url: `${com.basePath}/elevator-web/qr/create`,
          data: {
            width: "200",
            heigh: "200",
            msg: this.dataTableObj.checkCodes
          },
          responseType: 'blob'
        }).then(response => {
          if (response.data instanceof Blob) {
            this.download(response)
          }else {
            this.$message.error(response.data.message)
          }
        }).catch((error) => {
          if (error.data.code === '401') {
            this.$message.error(error.data.message)
          } else {
            this.downLoad(error.data)
          }
        })
      },
      // 下载文件
      downLoad(data) {
        if (!data) {
          return
        }
        let url = window.URL.createObjectURL(new Blob([data]))
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', '电梯二维码.zip')

        document.body.appendChild(link)
        link.click()
      },
      // 默认勾选
      toggleSelection(rows) {
        this.$refs.chooseEle.toggleChange(rows);
      },

      // 页面刷新
      pageReload(){
        this.getEleTestingData();
      }
    }
  }
</script>
<style lang="scss" type="text/scss">
  @import "../../../style/entry/components/pageCommon";
</style>

